// 项目推荐页面功能
class ProjectRecommendation {
    constructor() {
        this.projects = [];
        this.recommendations = {};
        this.updateInterval = null;
        this.currentVisitorId = null;
    }

    // 初始化页面
    async initialize() {
        this.currentVisitorId = this.getVisitorId();
        
        if (!this.currentVisitorId) {
            Utils.showNotification('请先登录', 'warning');
            navigateTo('login.html');
            return;
        }

        await this.loadVisitorPriority();
        await this.loadProjects();
        await this.loadRecommendations();
        
        this.setupEventListeners();
        this.startAutoUpdate();
    }

    // 获取游客ID
    getVisitorId() {
        const user = getCurrentUser();
        return user ? user.id : localStorage.getItem('visitorId');
    }

    // 加载游客优先级信息
    async loadVisitorPriority() {
        try {
            const visitor = await apiService.getVisitorInfo();
            this.updatePriorityIndicator(visitor.priority);
        } catch (error) {
            console.error('Failed to load visitor priority:', error);
        }
    }

    // 更新优先级指示器
    updatePriorityIndicator(priority) {
        const indicator = document.getElementById('priorityIndicator');
        const badge = indicator.querySelector('.priority-badge');
        
        if (priority === 'high' || priority === 'urgent') {
            indicator.style.display = 'block';
            badge.className = `priority-badge ${priority}`;
            badge.innerHTML = `
                <span class="priority-icon">⭐</span>
                <span>${priority === 'high' ? '高优先级游客' : '紧急优先级游客'} - 可优先分配项目</span>
            `;
        } else {
            indicator.style.display = 'none';
        }
    }

    // 加载项目列表
    async loadProjects() {
        try {
            this.projects = await apiService.getAllProjects();
            this.renderProjectList();
            this.updateProjectSelect();
        } catch (error) {
            console.error('Failed to load projects:', error);
            // 使用模拟数据作为后备
            this.loadMockProjects();
        }
    }

    // 加载推荐信息
    async loadRecommendations() {
        try {
            this.recommendations = await apiService.getProjectRecommendations();
            this.updateRecommendationCards();
        } catch (error) {
            console.error('Failed to load recommendations:', error);
            // 使用模拟推荐数据
            this.loadMockRecommendations();
        }
    }

    // 渲染项目列表
    renderProjectList() {
        const container = document.querySelector('.project-list-full');
        if (!container) return;

        container.innerHTML = this.projects.map(project => `
            <div class="project-item" data-project-id="${project.id}">
                <div class="project-main">
                    <span class="project-icon">${this.getProjectIcon(project.name)}</span>
                    <span class="project-name">${project.name}</span>
                </div>
                <div class="project-status">
                    <span class="wait-time">${project.waitTime}分钟</span>
                    <span class="status ${project.status}">
                        ${this.getStatusText(project.status)}
                    </span>
                    <button class="btn btn-sm btn-primary" 
                            onclick="projectRecommendation.reserveProject('${project.id}')"
                            ${project.status !== 'available' ? 'disabled' : ''}>
                        预约
                    </button>
                </div>
            </div>
        `).join('');
    }

    // 更新项目选择下拉框
    updateProjectSelect() {
        const select = document.getElementById('selectedProject');
        if (!select) return;

        select.innerHTML = '<option value="">请选择游乐项目</option>' +
            this.projects
                .filter(project => project.status === 'available')
                .map(project => `
                    <option value="${project.id}">${project.name} (排队${project.waitTime}分钟)</option>
                `).join('');
    }

    // 更新推荐卡片
    updateRecommendationCards() {
        const bestProject = this.recommendations.bestProject;
        const nearestProject = this.recommendations.nearestProject;

        if (bestProject) {
            document.getElementById('bestProjectName').textContent = bestProject.name;
            document.getElementById('bestWaitTime').textContent = bestProject.waitTime;
            document.getElementById('bestDistance').textContent = bestProject.distance;
        }

        if (nearestProject) {
            document.getElementById('nearestProjectName').textContent = nearestProject.name;
            document.getElementById('nearestWaitTime').textContent = nearestProject.waitTime;
            document.getElementById('nearestDistance').textContent = nearestProject.distance;
        }

        // 更新推荐项目列表
        this.renderRecommendedProjects();
    }

    // 渲染推荐项目列表
    renderRecommendedProjects() {
        const container = document.getElementById('recommendedProjects');
        if (!container) return;

        const recommended = this.recommendations.recommendedProjects || [];
        container.innerHTML = recommended.map(project => `
            <div class="project-item">
                <div class="project-main">
                    <span class="project-icon">${this.getProjectIcon(project.name)}</span>
                    <div class="project-info">
                        <span class="project-name">${project.name}</span>
                        <span class="project-reason">${project.recommendationReason}</span>
                    </div>
                </div>
                <div class="project-status">
                    <span class="wait-time">${project.waitTime}分钟</span>
                    <button class="btn btn-sm btn-primary" 
                            onclick="projectRecommendation.reserveProject('${project.id}')">
                        立即预约
                    </button>
                </div>
            </div>
        `).join('');
    }

    // 预约项目
    async reserveProject(projectId, type = 'direct') {
        let targetProjectId = projectId;

        if (type === 'best') {
            targetProjectId = this.recommendations.bestProject?.id;
        } else if (type === 'nearest') {
            targetProjectId = this.recommendations.nearestProject?.id;
        }

        if (!targetProjectId) {
            Utils.showNotification('请先选择项目', 'warning');
            return;
        }

        const project = this.projects.find(p => p.id === targetProjectId);
        if (!project) {
            Utils.showNotification('项目不存在', 'error');
            return;
        }

        if (project.status !== 'available') {
            Utils.showNotification('该项目当前不可用', 'warning');
            return;
        }

        // 显示预约表单
        this.showReservationForm(project);
    }

    // 显示预约表单
    showReservationForm(project) {
        const form = document.getElementById('reservationForm');
        const projectSelect = document.getElementById('selectedProject');
        
        if (projectSelect) {
            projectSelect.value = project.id;
        }
        
        form.style.display = 'block';
        form.scrollIntoView({ behavior: 'smooth' });
    }

    // 提交预约
    async submitReservation(event) {
        event.preventDefault();
        
        const formData = new FormData(event.target);
        const projectId = formData.get('projectId') || document.getElementById('selectedProject').value;
        const reservationTime = formData.get('reservationTime');
        const visitorCount = parseInt(formData.get('visitorCount'));

        if (!projectId || !reservationTime || !visitorCount) {
            Utils.showNotification('请填写完整的预约信息', 'warning');
            return;
        }

        const reservationData = {
            visitorId: this.currentVisitorId,
            projectId: projectId,
            reservationTime: reservationTime,
            visitorCount: visitorCount
        };

        try {
            const result = await apiService.reserveProject(projectId);
            Utils.showNotification('预约成功！', 'success');
            this.hideReservationForm();
            this.updateProjectStatus(projectId, 'reserved');
        } catch (error) {
            console.error('Reservation failed:', error);
            Utils.showNotification('预约失败，请重试', 'error');
        }
    }

    // 隐藏预约表单
    hideReservationForm() {
        const form = document.getElementById('reservationForm');
        form.style.display = 'none';
        form.reset();
    }

    // 取消预约
    cancelReservation() {
        this.hideReservationForm();
    }

    // 更新项目状态
    updateProjectStatus(projectId, status) {
        const project = this.projects.find(p => p.id === projectId);
        if (project) {
            project.status = status;
            this.renderProjectList();
        }
    }

    // 设置事件监听器
    setupEventListeners() {
        const reservationForm = document.getElementById('projectReservationForm');
        if (reservationForm) {
            reservationForm.addEventListener('submit', (e) => this.submitReservation(e));
        }

        // 实时搜索项目
        const searchInput = document.getElementById('projectSearch');
        if (searchInput) {
            searchInput.addEventListener('input', Utils.debounce((e) => {
                this.filterProjects(e.target.value);
            }, 300));
        }

        // 更新时间显示
        this.updateTimeDisplay();
        setInterval(() => this.updateTimeDisplay(), 60000);
    }

    // 过滤项目
    filterProjects(searchTerm) {
        const filteredProjects = this.projects.filter(project => 
            project.name.toLowerCase().includes(searchTerm.toLowerCase())
        );
        this.renderFilteredProjects(filteredProjects);
    }

    // 渲染过滤后的项目
    renderFilteredProjects(projects) {
        const container = document.querySelector('.project-list-full');
        if (!container) return;

        container.innerHTML = projects.map(project => `
            <div class="project-item" data-project-id="${project.id}">
                <div class="project-main">
                    <span class="project-icon">${this.getProjectIcon(project.name)}</span>
                    <span class="project-name">${project.name}</span>
                </div>
                <div class="project-status">
                    <span class="wait-time">${project.waitTime}分钟</span>
                    <span class="status ${project.status}">
                        ${this.getStatusText(project.status)}
                    </span>
                    <button class="btn btn-sm btn-primary" 
                            onclick="projectRecommendation.reserveProject('${project.id}')"
                            ${project.status !== 'available' ? 'disabled' : ''}>
                        预约
                    </button>
                </div>
            </div>
        `).join('');
    }

    // 开始自动更新
    startAutoUpdate() {
        this.updateInterval = setInterval(async () => {
            await this.loadProjects();
            await this.loadRecommendations();
            Utils.showNotification('数据已更新', 'info');
        }, CONFIG.UPDATE_INTERVAL);
    }

    // 停止自动更新
    stopAutoUpdate() {
        if (this.updateInterval) {
            clearInterval(this.updateInterval);
            this.updateInterval = null;
        }
    }

    // 更新时间显示
    updateTimeDisplay() {
        const timeElement = document.getElementById('updateTime');
        if (timeElement) {
            timeElement.textContent = Utils.formatTime(new Date());
        }
    }

    // 工具函数
    getProjectIcon(projectName) {
        const iconMap = {
            '过山车': '🎢',
            '激流勇进': '💦',
            '大转盘': '🎡',
            '旋转木马': '🎠',
            'VR影院': '🎯',
            '大礼盒': '🎁',
            '默认': '🎪'
        };
        
        for (const [key, icon] of Object.entries(iconMap)) {
            if (projectName.includes(key)) {
                return icon;
            }
        }
        return iconMap['默认'];
    }

    getStatusText(status) {
        const statusMap = {
            'available': '可游玩',
            'maintenance': '维护中',
            'closed': '已关闭',
            'reserved': '已预约'
        };
        return statusMap[status] || '未知';
    }

    // 模拟数据（开发用）
    loadMockProjects() {
        this.projects = [
            {
                id: '1',
                name: '过山车',
                waitTime: 15,
                status: 'available',
                capacity: 20,
                currentQueue: 8,
                location: { x: 100, y: 200 }
            },
            {
                id: '2',
                name: '激流勇进',
                waitTime: 20,
                status: 'available',
                capacity: 15,
                currentQueue: 12,
                location: { x: 150, y: 180 }
            },
            {
                id: '3',
                name: '大转盘',
                waitTime: 25,
                status: 'available',
                capacity: 30,
                currentQueue: 18,
                location: { x: 200, y: 250 }
            },
            {
                id: '4',
                name: '旋转木马',
                waitTime: 5,
                status: 'available',
                capacity: 25,
                currentQueue: 3,
                location: { x: 180, y: 220 }
            },
            {
                id: '5',
                name: 'VR影院',
                waitTime: 30,
                status: 'maintenance',
                capacity: 10,
                currentQueue: 0,
                location: { x: 220, y: 280 }
            }
        ];
        this.renderProjectList();
        this.updateProjectSelect();
    }

    loadMockRecommendations() {
        this.recommendations = {
            bestProject: {
                id: '4',
                name: '旋转木马',
                waitTime: 5,
                distance: 80
            },
            nearestProject: {
                id: '2',
                name: '激流勇进',
                waitTime: 20,
                distance: 50
            },
            recommendedProjects: [
                {
                    id: '4',
                    name: '旋转木马',
                    waitTime: 5,
                    recommendationReason: '排队时间最短'
                },
                {
                    id: '1',
                    name: '过山车',
                    waitTime: 15,
                    recommendationReason: '体验刺激，适合年轻人'
                },
                {
                    id: '2',
                    name: '激流勇进',
                    waitTime: 20,
                    recommendationReason: '距离最近，水上项目'
                }
            ]
        };
        this.updateRecommendationCards();
    }
}

// 创建全局实例
const projectRecommendation = new ProjectRecommendation();

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', function() {
    projectRecommendation.initialize();
});

// 导出到全局作用域
window.projectRecommendation = projectRecommendation;